class Collector {
  constructor() {
    this.INTERVAL_BASE = 1000;
    this.MAX_INTERVAL = 2000;
    this.scrollAttempts = 0;
    this.lastHeight = 0;
    this.staticCount = 0;
    this.isCollecting = false;
    this.observer = new MutationObserver(this.handleDomChanges.bind(this));
  }

  start() {
    this.observeDom();
    this.scheduleScroll();
  }

  observeDom() {
    this.observer.observe(document.documentElement, {
      childList: true,
      subtree: true,
      attributes: true,
    });
  }

  handleDomChanges(mutations) {
    if (!this.isCollecting) return;
    mutations.forEach((mutation) => {
      if (mutation.type === 'childList') {
        this.extractLinks();
      }
    });
  }

  scheduleScroll() {
    const dynamicInterval = Math.min(
      this.INTERVAL_BASE * Math.pow(2, this.scrollAttempts),
      this.MAX_INTERVAL
    );

    setTimeout(() => {
      this.scrollPage();
      this.checkTerminationConditions();
    }, dynamicInterval);
  }

  scrollPage() {
    window.scrollTo({
      top: document.documentElement.scrollHeight,
      behavior: 'smooth',
    });
    this.scrollAttempts++;
  }

  checkTerminationConditions() {
    const currentHeight = document.documentElement.scrollHeight;

    if (currentHeight === this.lastHeight) {
      if (++this.staticCount >= 3) {
        this.stop('auto');
        return;
      }
    } else {
      this.staticCount = 0;
      this.lastHeight = currentHeight;
    }

    this.scheduleScroll();
  }

  extractLinks() {
    const videoNodes = [...document.querySelectorAll('a[href*="/video/"]')];
    const links = videoNodes
      .map((node) => new URL(node.href).pathname.match(/\/video\/(\d+)/)?.[1])
      .filter(Boolean);

    chrome.runtime.sendMessage({
      type: 'newLinks',
      data: [...new Set(links)],
    });
  }

  stop(reason) {
    this.isCollecting = false;
    this.observer.disconnect();
    chrome.runtime.sendMessage({
      type: 'collectionStopped',
      reason: reason,
    });
  }
}

// 初始化采集器并与background建立通信
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'startCollection') {
    const collector = new Collector();
    collector.isCollecting = true;
    collector.start();
  }
});
